package com.bruce.cloud.feign.client;

import feign.Feign;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by bruce in 2025/6/18 22:04
 */
@Component
public class ClientFactory {

    @Autowired
    private HttpMessageConverters httpMessageConverters;

    private final ConcurrentHashMap<Class<?>, Object> clients = new ConcurrentHashMap<>();


    public <T> T create(Class<T> clientClass) {
        Object o = clients.get(clientClass);
        if (o != null) {
            return (T) o;
        }
        Object o1 = clients.computeIfAbsent(clientClass, k -> create0(clientClass));
        return (T) o1;
    }

    private  <T> T create0(Class<T> clientClass) {
        SpringEncoder encoder = new SpringEncoder(() -> httpMessageConverters);
        SpringDecoder decoder = new SpringDecoder(() -> httpMessageConverters);

        T target = Feign.builder()
                // .client(client)
                .encoder(new SpringFormEncoder(encoder))
                .decoder(decoder)
                //.options(new Request.Options(10, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, true))
                .contract(new SpringMvcContract())
                //.addCapability(micrometerObservationCapability)
                //.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
                .target(clientClass, "http://127.0.0.1:8080/service");
        return target;
    }


}
